<template>
  <el-card class="section-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>文档列表</span>
        <el-button-group>
          <el-button size="small" @click="refresh" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button size="small" @click="$emit('toggle-view')">
            <el-icon><Grid /></el-icon>
            切换视图
          </el-button>
        </el-button-group>
      </div>
    </template>

    <el-table :data="docs" v-loading="loading" border style="width: 100%">
      <el-table-column label="标题" prop="title" min-width="220">
        <template #default="{ row }">
          <strong>{{ row.title }}</strong>
          <div class="doc-meta">
            <el-tag
              v-for="tag in row.metadata?.tags || []"
              :key="tag"
              size="small"
              type="info"
            >{{ tag }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="来源" prop="metadata.source" width="180" />
      <el-table-column label="创建时间" width="160">
        <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="向量" width="120">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.vector">已生成</el-tag>
          <el-tag type="danger" v-else>未生成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button size="small" text type="primary" @click="$emit('edit', row)">编辑</el-button>
          <el-popconfirm title="确认删除该条文档吗？" @confirm="remove(row.id)">
            <template #reference>
              <el-button size="small" text type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import dayjs from 'dayjs';
import { computed, onMounted } from 'vue';
import { Refresh, Grid } from '@element-plus/icons-vue';
import { useDocsStore } from '@/stores/docs';

const emit = defineEmits(['edit', 'toggle-view']);

const docsStore = useDocsStore();

const docs = computed(() => docsStore.items);
const loading = computed(() => docsStore.loading);

function formatDate(value) {
  return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '-';
}

async function refresh() {
  await docsStore.fetchDocs();
}

async function remove(id) {
  await docsStore.deleteDoc(id);
  emit('edit', null);
}

onMounted(refresh);
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.doc-meta {
  margin-top: 6px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
</style>
